//
//  TestTableViewCell.m
//  YHtableViewCellHeightDemo
//
//  Created by apple on 17/4/15.
//  Copyright © 2017年 wax. All rights reserved.
//

#import "TestTableViewCell.h"

@interface TestTableViewCell()

@property (weak, nonatomic) IBOutlet UILabel *keyLabel;

@property (weak, nonatomic) IBOutlet UILabel *valueLabel;

@property (weak, nonatomic) IBOutlet UIView *valueView;

//计算高度
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *valueViewHeight;



//keyLabel的宽度约束
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *keyLabelWidth;

@end

@implementation TestTableViewCell


#define  ScreenW [UIScreen mainScreen].bounds.size.width

#define  ScreenH [UIScreen mainScreen].bounds.size.height

CGFloat margin = 10;

- (void)awakeFromNib {
    [super awakeFromNib];
  
    //设置内容行数
    _valueLabel.numberOfLines = 0;
    
    _valueLabel.font = [UIFont systemFontOfSize:14];
    
    _keyLabel.font = [UIFont systemFontOfSize:14];
}

+(instancetype)loadCell{

    return [[NSBundle mainBundle] loadNibNamed:@"TestTableViewCell" owner:nil options:nil].lastObject;
    
}

#pragma mark - setValue
-(void)setDataDic:(NSDictionary *)dataDic{

    _dataDic = dataDic;
    
    //设置显示
    
    _keyLabel.text = dataDic[@"myKey"];
    
    _valueLabel.text = dataDic[@"myValue"];
    
    //设置显示的view - 拿到数据后在设置-->Label才有frame！
    [self setupValueView];
    
}

-(void)setupValueView{

    //1.宽度
    
    
    ///这样算不出结果
    /*
    CGFloat keyLabelW = _keyLabel.frame.size.width;
    
    CGFloat valueVeiwW = ScreenW - keyLabelW - 3*margin;
    */

    //Value的内容
    NSString *str = _dataDic[@"myValue"];
    
    //key的内容
    NSString *contentKey = _keyLabel.text;
    
    NSStringDrawingOptions options = NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin;
    
    NSDictionary *attrDic = @{
                              NSFontAttributeName:[UIFont systemFontOfSize:14],
                              };

    CGRect rect2 = [contentKey boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, 14) options:options attributes:attrDic context:nil];
    
    NSLog(@"keylabel --> rect.width = %f",rect2.size.width);

    CGFloat keyLabelWidth = rect2.size.width;

    //修改宽度约束
    _keyLabelWidth.constant = keyLabelWidth + 1;
 
    //ValueLabel的宽度
    CGFloat valueViewWidth = ScreenW - keyLabelWidth - 3*margin;
    
    //计算frame（value 内容）
    CGRect rect = [str boundingRectWithSize:CGSizeMake(valueViewWidth, CGFLOAT_MAX) options:options attributes:attrDic context:nil];
    
    //修改约束！-->不用设置valueLabel的，因为整个label都在valueView上，直接设置View的高度约束
    
    CGFloat valueHeight = rect.size.height + margin;;
    
    NSLog(@"valueHeight = %f",valueHeight);
    
    //此时，由于在xib中，valueView有顶部 + 底部约束（cell 的高度 约= valueView的高度 -->系统会自己计算）
    _valueViewHeight.constant = valueHeight;
    
}

@end
